package com.aaa.tars.service.impl;

import com.aaa.tars.dao.AttractionAuditDao;
import com.aaa.tars.dao.DotDao;
import com.aaa.tars.entity.AttractionAudit;
import com.aaa.tars.entity.Dot;
import com.aaa.tars.entity.Scenic;
import com.aaa.tars.service.DotService;
import com.aaa.tars.util.Page;
import com.aaa.tars.util.Result;
import com.aaa.tars.util.ResultUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @FileName: DotServiceImpl
 * @Description: 景点服务实现类
 * @Author: 李宗盛
 * @CreateTime: 2025/9/11 8:52
 * @Version: 17
 */
@Service
public class DotServiceImpl implements DotService {
    @Resource
    private DotDao dotDao;
    @Resource
    private AttractionAuditDao attractionAuditDao;
    
    @Override
    public Dot queryById(Integer dotId) {
        return dotDao.queryById(dotId);
    }

    @Override
    public PageInfo queryByPage(Page<Dot> page) {
        //判断pageNo和pageSize 不能为空
        Integer pageNo=page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo==null||pageNo==0||pageSize==null||pageSize==0){
            throw  new IllegalArgumentException("非法参数异常");}
        PageHelper.startPage(pageNo,pageSize);
        Dot data=page.getData();
        return  new PageInfo(dotDao.queryAll(data));
    }

    @Override
    public PageInfo frontQueryByPage(Page<Dot> page) {
        //判断pageNo和pageSize 不能为空
        Integer pageNo=page.getPageNo();
        Integer pageSize = page.getPageSize();
        if (pageNo==null||pageNo==0||pageSize==null||pageSize==0){
            throw  new IllegalArgumentException("非法参数异常");}
        PageHelper.startPage(pageNo,pageSize);
        Dot data=page.getData();
        return  new PageInfo(dotDao.frontQueryAll(data));
    }

    @Override
    public int add(Dot dot) {

        // 1. 先插入景区数据，此时会触发主键回填
        int insertCount = dotDao.add(dot);
        // 检查插入是否成功
        if (insertCount>0) {
            // 2. 此时 dotId 已被数据库自动生成并回填
            Integer dotId = dot.getDotId();
            System.out.println("刚插入的scenicId：" + dotId);
            if (dotId != null) {
                // 3. 插入审核记录
                AttractionAudit attractionAudit = new AttractionAudit();
                attractionAudit.setDotId(dotId);
                attractionAudit.setAuditStatus("0"); // 0表示待审核
                //插入默认delFlag=0
                attractionAudit.setDelFlag("0");
                // 调用审计DAO插入
                attractionAuditDao.insert(attractionAudit);// 需要实现该方法
            }
        }
        return insertCount;
    }

    @Override
    public int update(Dot dot) {
        // 2. 查询是否存在审核记录
        AttractionAudit attractionAudit = attractionAuditDao.queryByDotId(dot.getDotId());

        if (attractionAudit != null) {
            // 若存在，更新审核状态
            attractionAudit.setAuditStatus("0");
            attractionAudit.setRejectReason("");
            attractionAudit.setDelFlag("0");
            attractionAudit.setAuditPeople("");
            //设置审核时间为空
            attractionAudit.setAuditTime(null);
            attractionAuditDao.update(attractionAudit);
        }
        return dotDao.update(dot);
    }

    @Override
    public int deleteById(Integer dotId) {
        //设置审核状态为景区已删除3
        AttractionAudit attractionAudit = new AttractionAudit();
        attractionAudit.setDotId(dotId);
        attractionAudit.setAuditStatus("3");
        attractionAuditDao.updateByDotId(attractionAudit);

        return dotDao.deleteById(dotId);
    }
    /**
     * 上传景区图片
     * @param file 上传的文件
     * @return 上传结果和文件路径
     */
    @Override
    public Result uploadImage(MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.error("上传文件为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType)) {
            return ResultUtil.error("只允许上传JPG/PNG格式的图片");
        }

        // 检查文件大小（最大10MB）
        long size = file.getSize();
        if (size > 10 * 1024 * 1024) {
            return ResultUtil.error("图片大小不能超过10MB");
        }

        try {
            // 获取项目根目录下的resources/static/img/scenic目录 (源代码目录)
            String srcPath = System.getProperty("user.dir") + "/src/main/resources/static/img/dot/";
            File srcDir = new File(srcPath);
            if (!srcDir.exists()) {
                srcDir.mkdirs();
            }

            // 获取target/classes/static/img/scenic目录 (编译后目录)
            String targetPath = System.getProperty("user.dir") + "/target/classes/static/img/dot/";
            File targetDir = new File(targetPath);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String newFilename = UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 保存文件到源代码目录
            String srcFilePath = srcPath + newFilename;
            file.transferTo(new File(srcFilePath));

            // 复制文件到target目录
            Files.copy(
                    new File(srcFilePath).toPath(),
                    new File(targetPath + newFilename).toPath(),
                    StandardCopyOption.REPLACE_EXISTING
            );

            // 返回可访问的URL路径
            String urlPath = "/img/dot/" + newFilename;
            Map<String, String> data = new HashMap<>();
            data.put("url", urlPath);

            return ResultUtil.success(data);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    public List<Dot> queryByScenicId(Integer scenicId) {
        return dotDao.queryByScenicId(scenicId);
    }
}